﻿using OrchardCore.ContentManagement.Display.ContentDisplay;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ruitu.Edu.TrainingDemo.Models;
using OrchardCore.DisplayManagement.Views;
using OrchardCore.ContentManagement.Display.Models;
using Ruitu.Edu.TrainingDemo.ViewModels;
using OrchardCore.DisplayManagement.Handlers;


namespace Ruitu.Edu.TrainingDemo.Drivers
{
    public class PersonPartDisplayDriver : ContentPartDisplayDriver<PersonPart>
    {
        public override IDisplayResult Display(PersonPart part, BuildPartDisplayContext context)
        {
            return Initialize<PersonPartViewModel>(GetDisplayShapeType(context), viewModel => PopulateViewModel(part, viewModel))
                .Location("Detail", "Content:1")
                .Location("Summary", "Content:1");

        }

        public override IDisplayResult Edit(PersonPart part, BuildPartEditorContext context)
        {
            return  Initialize<PersonPartViewModel>(GetEditorShapeType(context), viewModel => PopulateViewModel(part, viewModel));
        }

        public override async Task<IDisplayResult> UpdateAsync(PersonPart part, UpdatePartEditorContext context)
        {
            //var viewModel = await context.CreateModelAsync<PersonPartViewModel>(Prefix);
            var viewModel = new PersonPartViewModel();
            
            await context.Updater.TryUpdateModelAsync(viewModel, Prefix);

            part.BirthDateUtc = viewModel.BirthDateUtc;
            part.Name = viewModel.Name;
            part.Handedness = viewModel.Handedness;

            return await EditAsync(part, context);
        }

        private static void PopulateViewModel(PersonPart part, PersonPartViewModel viewModel)
        {
            viewModel.PersonPart = part;
            viewModel.Name = part.Name;
            viewModel.BirthDateUtc = part.BirthDateUtc;
            viewModel.Handedness = part.Handedness;
        }
    }
}
